import router from "@/router/index.ts";
import { userMode } from "@/stores/user";
import { settingMode } from "@/stores/setting";


router.beforeEach(async (to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title + ' - Admin Web 管理系统'
    }
    const userStore = userMode()
    const settingsStore = settingMode()

    // 初始化设置
    settingsStore.initTheme()

    if (to.path === '/') {
        if (userStore.token || localStorage.getItem('token')) return next('/dashboard')
        return next({ path: '/login', query: { redirect: to.fullPath } })
    }
    // 1.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由并放行到登陆页
    if (to.path === '/login') {
        if (userStore.token || localStorage.getItem('token')) return next(from.fullPath)
        return next()
    }

    // 2.判断访问页面是否在路由白名单(不需要登陆)地址中，如果存在直接放行
    if (['404'].includes(to.path)) return next()

    // 3.判断是否有 Token，没有token跳转到登陆页面并且携带原目标路径
    if (!userStore.token && !localStorage.getItem('token')) {
        return next({ path: '/login', query: { redirect: to.fullPath } })
    }

    next()


});

router.afterEach(() => {
});